<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <ul>
        <li><router-link to="/">Home</router-link></li>
        <li><router-link to="/admin">Admin</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
    <script src="vue.js"></script>
    <script src="vue-router.js"></script>
    <script>
      const Home = {
        template: `<div>Home</div>`,
      };
      const Admin = {
        template: `<div>Admin</div>`,
      };
      const routes = [
        { 
          name: "home", 
          path: "/", 
          component: Home 
        },
        { 
          name: "admin", 
          path: "/admin", 
          component: Admin 
        }
      ];

      var router = new VueRouter({
        routes,
      });
      router.onError(error=>console.error('捕获到了错误'));
      router.beforeEach((to,from,next)=>{
        //如果直接调用next方法并且不传递任何参数，则表示正常导航 
        //next();
        //next('/login');
        //next(false);
        //next(new Error('手工抛错误'));
        if(to.path === '/admin'){
          router.push('/xxx');
        }else{
          next();
        }
       
      });
      var vm = new Vue({
        el: "#app",
        router,
      });
      const {isNavigationFailure,NavigationFailureType} = VueRouter;
      //{redirected: 2, aborted: 4, cancelled: 8, duplicated: 16}
      //console.log(isNavigationFailure,NavigationFailureType)
      router.push('/admin').catch(failure=>{
        if(isNavigationFailure(failure,NavigationFailureType.duplicated)){
          console.log('试图导航到当前的位置',failure);
        }else if(isNavigationFailure(failure,NavigationFailureType.redirected)){
          //重定向到了别的路径 Error: Redirected when going from "/" to "/admin" via a navigation guard.
          console.log('重定向到了别的路径',failure);
        }else if(isNavigationFailure(failure,NavigationFailureType.cancelled)){
          //重定向到了别的路径 Error: Redirected when going from "/" to "/admin" via a navigation guard.
          console.log('取消了路径跳转',failure);
        }else if(isNavigationFailure(failure,NavigationFailureType.aborted)){
          //跳转中止了 Error: Navigation aborted from "/" to "/admin" via a navigation guard.
          console.log('跳转中止了',failure);
        }
      });
    </script>
  </body>
</html>
